"use strict"

root = exports ? this

root.furion = ((mod)->
  mod.utils = {}

  mod.utils.sendDelegate = (data, purchase_amount_display=null)->
    if not purchase_amount_display?
      data.purchase_amount_display = data.purchase_amount
    else
      data.purchase_amount_display = purchase_amount_display
    switch data.type
      when 'fixed'
        data.package_id = data.id
      when 'transfer'
        data.transfer_id = data.id
    params = {}
    options = ['type','package_id', 'transfer_id', 'purchase_amount', 'purchase_amount_display', 'is_recharge', 'di_yong_quan_id_list']
    for i in options
      params[i] = if data[i] == undefined then '' else data[i]
    return params

  mod.utils.getPrerequisiteParams = (pay, quan_id_type_json, payment_type)->
    params =
      is_wap: if furion.utils.isDevice() then false else true
      payment_type: payment_type

    if pay.is_recharge # recharge
      params.recharge =
        money: pay.purchase_amount,
        card_id: pay.card_id
    else # delegate
      params.delegate =
        product_type: pay.type
        shares: pay.purchase_amount
        payment_type: pay.payment_type
        card_id: pay.card_id
        quan_id_type_json: quan_id_type_json
      switch pay.type
        when 'fixed'
          params.delegate.fixed =
            package_id: pay.package_id
        when 'transfer'
          params.delegate.transfer =
            transfer_id: pay.transfer_id
    return params

  mod.utils.NumberFloor = (value, digit=2)->
    v = if value then value.toString() else '0'
    pos_decimal = v.indexOf('.')
    if pos_decimal < 0
      pos_decimal = v.length
      v += ".0"
    while v.length <= pos_decimal + digit
      v += '0'
    len = pos_decimal + digit + 1
    len -= 1 if digit <= 0
    return v.substr(0,  len)

  mod.utils.verifyPhone = (phone)->
    return {result: false, data: '不正确的手机号'} if !phone
    regex = /^1[3-8][0-9]{9}$/
    if regex.test phone
      return {result: true, data: ''}
    else
      return {result: false, data: '不正确的手机号'}

  mod.utils.verifyPassword = (password)->
    return {result: false, data: '密码必须6位字符以上'} if !password || password.length < 6
    return {result: true, data: ''}
    # # regex = /^[A-Za-z0-9_-]{6,18}$/
    # regex = /^[a-zA-Z0-9!@#$%^&*_-]{6,16}$/
    # if password.match regex
    #   return {result: true, data: ''}
    # else
    #   return {result: false, data: '密码含有非法字符'}

  mod.utils.verifySmsCode = (code)->
    return {result: false, data: '验证码必须为6位数字组合'} if !code
    regex = /^\d{6}$/
    if code.match regex
      return {result: true, data: ''}
    else
      return {result: false, data: '验证码必须为6位数字组合'}

  mod.utils.isDevice = ()->
    typeof(ionic.Platform.device().platform) != "undefined"

  mod.utils.checkCardCertify = (account)->
    result = { result: true }
    if !account.has_pay_pwd
      result =
        result: false
        msg: '请先设置交易密码'
        state: 'pay-password'
    else if account.bank_cards.length == 0
      result =
        result: false
        msg: '请先绑定银行卡'
        state: 'auth'
    else if !account.authenticated
      cid = account.bank_cards[0].id
      result =
        result: false
        msg: '您的银行卡未通过，如需帮助请联系客服'
        state: 'auth'
        params: {cid: cid}
    return result

  mod.utils.upgradeApp = (data, $ionicPopup)->
    console.debug data
    popup = $ionicPopup.show(
      template: "<p>发布新版本啦：#{data.latest_version}<p>"
      title: '请升级至最新版'
      subTitle: ''
      buttons: [
        {
          text: '<b>去升级</b>'
          type: 'button-positive'
          onTap: (e) ->
            if ionic.Platform.isIOS()
              window.open(data.app_url_ios, '_system')
            else
              window.open(data.app_url_android, '_system')
            e.preventDefault()
        }
      ])

  mod.storage = {}

  mod.storage.account = ()->
    data = window.localStorage['rt-account']

    account = if data
      try
        JSON.parse(data)
      catch e
        console.debug e
        {}
    else
      {}

    return account

  mod.storage.updatePopupMsg= (id)->
    content = window.localStorage['rt-sys-msg']
    data = if content then JSON.parse(content) else {}
    data[id] = true
    window.localStorage['rt-sys-msg'] = JSON.stringify data
    return

  mod.storage.checkPopupMsg = (id)->
    content = window.localStorage['rt-sys-msg']
    data = if content then JSON.parse(content) else {}
    return data[id]

  mod.storage.deleteAccount = ()->
    window.localStorage.removeItem 'rt-account'
    mod.storage.deleteGesture()
    window.furionPush.jpush.setAlias()

  mod.storage.updateAccount = ( data )->
    account_data = window.localStorage['rt-account']

    account = if account_data
      try
        JSON.parse(account_data)
      catch e
        console.debug e
        {}
    else
      {}

    for key of data
      account[key] = data[key]

    window.localStorage['rt-account'] = JSON.stringify account
    return account

  mod.storage.isLogin = ()->
    account = mod.storage.account()
    if account.session_id && account.phone
      return true
    else
      return false

  mod.storage.accountLogin = (params)->
    account = params.account.account
    mod.storage.updateAccount account

    # 更新数据
    mod.storage.updateAccount
      session_id: params.account.session_id

    # 手势密码相关
    gs = params.gs
    gs.updatePattern(account.gesture, account.gesture_enabled)
    if gs.needNotification() # 提醒还没设置手势
      # params.toast.show "您尚未设置手势密码，请前去设置中心设置"
      gs.setNotified()

    window.furionPush.jpush.setAlias()

    # 关闭页面
    # params.scope.$emit 'close-all-modals'

    # 跳转到上一个需要登陆后才能进的页面
    pp = params.params # {state: null, params: null}
    if pp && pp.state
      if pp.state == 'gesture-login'
        # alert pp.state
        params.state.go 'app.account'
      else
        params.state.go pp.state, pp.params
    else
      params.state.go 'app.account'

  mod.storage.deleteGesture = ()->
    window.localStorage.removeItem 'gesture_pattern'
    window.localStorage.removeItem 'gesture_enabled'
    window.localStorage.removeItem 'gesture_setting_notified'

  mod.storage.deviceInfo = ()->
    data = window.localStorage['rt-device-info']
    info = if data then JSON.parse(data) else {}
    return info

  mod.storage.updateDeviceInfo = ( data )->
    info_data = window.localStorage['rt-device-info']
    info = if info_data then JSON.parse(info_data) else {}
    for key of data
      info[key] = data[key]
    window.localStorage['rt-device-info'] = JSON.stringify info
    return info

  return mod
)(window.furion || {})
